package com.yb.proxy.cglib;

import java.lang.reflect.Method;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import com.yb.proxy.MonitorSession;

public class CglibProxy implements MethodInterceptor{
	
	private static CglibProxy cp = new CglibProxy();
	
	public CglibProxy(){}
	
	public static CglibProxy getInstance(){
		return cp;
	}
	
	private Enhancer enhancer = new Enhancer();

	@Override
	public Object intercept(Object arg0, Method arg1, Object[] arg2,MethodProxy arg3) throws Throwable{
		MonitorSession.begin(arg1.getName());
		Object object = arg3.invokeSuper(arg0, arg2);
		MonitorSession.end();
		return object;
	}
	
	@SuppressWarnings("unchecked")
	public <T>T getProxy(Class<T> clazz){
		//使这个类成为所代理类的子类
		enhancer.setSuperclass(clazz);
		enhancer.setCallback(this);
		return (T)enhancer.create();
	}
}
